package yxy.game.pm2.command.hero;

import yxy.cherry.data.script.fomula;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.hero.HeroHandle;
import yxy.game.pm2.module.hero.HeroModule;

import java.util.Collection;

/**
 * 武将 武将重生
 */
@MessageType(proto = Command.HeroRebirth, classtype = HeroMessage.HeroRebirthRequest.class)
public class CMD_HeroRebirth extends Command<HeroMessage.HeroRebirthRequest> {

    @Override
    public void execute(MessageSource messageSource, HeroMessage.HeroRebirthRequest request) {
        String playerCode = messageSource.getTag();
        String code = request.getCode();

        HeroMessage.HeroRebirthResponse.Builder response = HeroMessage.HeroRebirthResponse.newBuilder();

        try {
            HeroModule heroModule = HeroModule.get(playerCode);
            int times = fomula.武将重生每日使用次数.intValue() - heroModule.getRebirthTimes() < 0 ? 0 : fomula.武将重生每日使用次数.intValue() - heroModule.getRebirthTimes();
            int money = fomula.武将重生每日使用次数.intValue() - heroModule.getRebirthTimes() <= 0 ? 50 : 0;
            HeroHandle heroHandle = new HeroHandle();
            Hero hero = heroHandle.getHero(playerCode, code);
            if (hero == null) {
                send(messageSource, response, Result.ParamError);
                return;
            }

            if (hero.getLevel() <= 1) {
                send(messageSource, response, Result.ParamError);// 不能重生
                return;
            }

            Collection<Currency> back = heroHandle.returnBack(playerCode, hero);

            response.addAllBack(new CurrencyHandle().packItems(back));

            response.setTimes(times);

            response.setMoney(money);

            send(messageSource, response, Result.Success);

        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }
    }

    private void send(MessageSource messageSource, HeroMessage.HeroRebirthResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}